
package com.example.quicklaunch;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBOperator {
    private final Uri URI = Uri.parse("content://" + AppListProvider.AUTHORITY + "/app");
    private Context mContext;
    private static final String REMOVE_PACKAGE = AppDataBaseHelper.APP_CLOUMN_PACKAGE + "=?";

    public DBOperator(Context context) {
        this.mContext = context;
    }

    public void onPackageRemoved(String packageName) {
        mContext.getContentResolver().delete(URI, REMOVE_PACKAGE, new String[] {
                packageName
        });
    }

    public void newPackage(AppItem item) {
        mContext.getContentResolver().insert(URI, bindValue(item));
    }

    private ContentValues bindValue(AppItem item) {
        ContentValues values = new ContentValues();
        values.put(AppDataBaseHelper.APP_CLOUMN_CLASS_NAME, item.getAppClassName());
        values.put(AppDataBaseHelper.APP_CLOUMN_LABEL, item.getAppLable());
        values.put(AppDataBaseHelper.APP_CLOUMN_LOOKUP, item.getLablePinyin());
        values.put(AppDataBaseHelper.APP_CLOUMN_PACKAGE, item.getAppPackage());
        return values;
    }

    public void updatePackage(AppItem item) {
        mContext.getContentResolver().update(URI, bindValue(item), null, null);
    }

    public void init(List<AppItem> items) {
        for (AppItem item : items) {
            newPackage(item);
        }
    }

    public Map<String, String> pinyinSaved() {
        Map<String, String> output = new HashMap<String, String>();
        Cursor cursor = null; 
        try {
            cursor = mContext.getContentResolver().query(URI, new String[] {
                    AppDataBaseHelper.APP_CLOUMN_LABEL, AppDataBaseHelper.APP_CLOUMN_LOOKUP
            }, null, null, null);
            while (cursor.moveToNext()) {
                output.put(cursor.getString(0), cursor.getString(1));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return output;
    }
}
